# -*- coding: utf-8 -*
import re
import subprocess

from ..common import Collector
from typing import List
import numpy as np

NETWORK_METRICS_NUM = 8


class NetMetricCollect(Collector):
    """网络性能数据收集器：包括带宽、丢包率和吞吐量，具体收集指标为 rxkB/s, txkB/s, rxpck/s, txpck/s, %ifutil"""

    def __init__(self, is_test):
        super().__init__(is_test)

    def collect(self) -> None:
        number_pat = re.compile(r"\d+\.\d+")
        every_line: List[List[float]] = []
        average: List[float] = []
        if self.is_test:
            test_file_path = Collector.get_test_file_path("sar.txt", __file__)
            with open(test_file_path, "r", encoding="utf-8") as f:
                lines = f.readlines()
            out_str = "".join(lines)
        else:
            process_out = subprocess.run(["sar", "-n", "DEV", "1", "1"], stdout=subprocess.PIPE,
                                         stderr=subprocess.PIPE)
            out_str = str(process_out.stdout, encoding="utf-8")
            start_pos = out_str.find("平均时间")
            out_str = out_str[start_pos:]

            # 查询主要网口
            process_out = subprocess.run(["ifconfig"], stdout=subprocess.PIPE,
                                         stderr=subprocess.PIPE)
            network_info = str(process_out.stdout, encoding="utf-8")
            end_pos = network_info.find(":")
            main_net_port = network_info[:end_pos]
            out_str = out_str[out_str.find(main_net_port):]

        metrics_list: List[float] = list(map(float, number_pat.findall(out_str)))
        for i in range(0, len(metrics_list), NETWORK_METRICS_NUM):
            every_line.append(metrics_list[i:i + NETWORK_METRICS_NUM])
        every_line_np = np.array(every_line)
        totsum = np.sum(every_line_np, axis=0)
        ave_np = np.divide(totsum, len(metrics_list) / NETWORK_METRICS_NUM)
        average = ave_np.tolist()
        self.stash.extend(average[:4])
        self.stash.append(average[-1])
